package com.myproject.adapter;

import java.util.ArrayList;

import com.myproject.model.Deal;
import com.myproject.source.R;
import com.myproject.source.image.ImageLoader;

import android.app.Activity;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;

public class DealAdapter extends ArrayAdapter<Deal> {
	private final Activity activity;
	private ArrayList <Deal> deals;
	private ArrayList <Deal> filtereddeals;
	private ImageLoader imageLoader;
	private DealCampaignFilter filter;
	public DealAdapter(Activity activity, ArrayList<Deal> objects) {
		super(activity, R.layout.deal_list_item, objects);
		this.activity = activity;
		this.deals = objects;
		imageLoader = new ImageLoader(activity.getApplicationContext());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		DealView dealView = null;
		
		if (rowView == null) {
			// Get a new instance of the row layout view
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.deal_list_item, null);

			// Hold the view objects in an object,
			// so they don't need to be re-fetched
			dealView = new DealView();
			dealView.name = (TextView) rowView.findViewById(R.id.name);
			dealView.description = (TextView) rowView
					.findViewById(R.id.description);
			dealView.listPrice = (TextView) rowView
					.findViewById(R.id.listPrice);
			dealView.ourPrice = (TextView) rowView.findViewById(R.id.ourPrice);
			dealView.thumb = (ImageView) rowView.findViewById(R.id.image);
			// Cache the view objects in the tag,
			// so they can be re-accessed later
			rowView.setTag(dealView);
		} else {
			dealView = (DealView) rowView.getTag();
		}

		// Transfer the stock data from the data object
		// to the view objects
		Deal currentdeal = (Deal) deals.get(position);
		dealView.name.setText(currentdeal.getName());
		dealView.description.setText(currentdeal.getDescription());
		dealView.listPrice.setText(currentdeal.getListPrice().toString());
		dealView.ourPrice.setText(currentdeal.getOurPrice().toString());
		dealView.listPrice.setPaintFlags(dealView.listPrice.getPaintFlags()
				| Paint.STRIKE_THRU_TEXT_FLAG);
		dealView.thumb.setContentDescription(currentdeal.getName());
		imageLoader.DisplayImage(currentdeal.getThumbUrl(), dealView.thumb);
		return rowView;
	}

	public void filterDeals(String filter)
    {
        // Create new empty list to add matched elements to
		ArrayList<Deal> filtered = new ArrayList<Deal>();

        // examine each element to build filtered list
        // remember to always use your original items list
		for(int i = 0, l = deals.size(); i < l; i++)
        {

           
            if (deals.get(i).getCampaignId().contains(filter))
            {
                filtered.add(deals.get(i));
            }
        }

        //set new (filterd) current list of items
        this.deals = filtered;

        //notify ListView to Rebuild
        notifyDataSetChanged();
     
    }
	@Override
    public Filter getFilter()
    {
        if(filter == null)
            filter = new DealCampaignFilter();
        return filter;
    }

    private class DealCampaignFilter extends Filter
    {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            // NOTE: this function is *always* called from a background thread, and
            // not the UI thread.
            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if(constraint != null && constraint.toString().length() > 0)
            {
                ArrayList<Deal> filt = new ArrayList<Deal>();
                ArrayList<Deal> lItems = new ArrayList<Deal>();
                synchronized (this)
                {
                    lItems.addAll(deals);
                }
                for(int i = 0, l = lItems.size(); i < l; i++)
                {
                    Deal d = lItems.get(i);
                    if(d.getCampaignId().contains(constraint))
                        filt.add(d);
                }
                result.count = filt.size();
                result.values = filt;
            }
            else
            {
                synchronized(this)
                {
                    result.values = deals;
                    result.count = deals.size();
                }
            }
            return result;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            // NOTE: this function is *always* called from the UI thread.
        	filtereddeals = (ArrayList<Deal>)results.values;
            notifyDataSetChanged();
            clear();
            for(int i = 0, l = filtereddeals.size(); i < l; i++)
                add(filtereddeals.get(i));
            notifyDataSetInvalidated();
        }

    }
	protected static class DealView {
		protected TextView name;
		protected TextView description;
		protected TextView listPrice;
		protected TextView ourPrice;
		protected ImageView thumb;
	}
}
